﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Yoozoo.Editor.Utils.AssetStandard;
using Yoozoo.Gta.ProjBuilder;
using Yoozoo.Managers.ResourceManagerV2.Editor.ResourceTools;
using Yoozoo.Managers.ResourceManagerV2.Framework.Resource;

namespace Yoozoo.Managers.ResourceManagement
{
    public class SubPackage
    {
        // 开启后默认进行收集
#if false
        [InitializeOnLoadMethod]
        private static void InitializeOnLoadMethod()
        {
            EditorApplication.update += OnUpdate;
        }

        private static bool isChecking;

        private static void OnUpdate()
        {
            if (Application.isPlaying)
            {
                if (!isChecking)
                {
                    isChecking = true;
                    SubPackageTool.Collect();
                }
            }
            else
            {
                isChecking = false;
            }
        }
#endif

        [MenuItem("GTATools/打包/收集RPG模式的资源")]
        public static void CollectRpgAssets()
        {
            if (!Application.isPlaying)
            {
                Debug.LogError("要先在编辑器中运行游戏");
                return;
            }

            SubPackageTool.CollectRpgAssets();
        }

        //[MenuItem("GTATools/打包/保存使用到的Asset Bundle")]
        public static void DumpAssets()
        {
            // 统计所有用到的Resource
            var collectResourcesSet = ResourceManager.ResourceLoader.collectResources;
            var collectResourceList = collectResourcesSet.ToList();
            collectResourceList.Sort();

            string file = EditorUtility.SaveFilePanel("保存到", "", "resources-" + DateTime.Now.ToString("yyyyMMddhhmmss"),
                "txt");
            if (!string.IsNullOrEmpty(file))
            {
                using (StreamWriter streamWriter = new StreamWriter(File.Open(file, FileMode.Create)))
                {
                    foreach (var resource in collectResourceList)
                    {
                        streamWriter.WriteLine(resource);
                    }
                }
            }

            Debug.LogFormat("保存完毕, 共计{0}个资源包", collectResourceList.Count);

            // 创建 AssetPackListCollection
            var collectAssetSet = ResourceManager.ResourceLoader.collectAssets;
            var collectAssetList = collectAssetSet.ToList();
            collectAssetList.Sort();

            var collection = new AssetPackListCollection();
            collection.Load();
            foreach (var assetName in collectAssetList)
            {
                if (SubPackageTool.IsKnownRpgAsset(assetName.ToLowerInvariant()))
                {
                    Debug.LogFormat("asset skipped. {0}", assetName);
                }
                else
                {
                    Debug.LogFormat("asset added. {0}", assetName);
                    collection.AssignAsset(assetName, "rpg");
                }
            }
            collection.Save();
        }


        //[MenuItem("GTATools/打包/仅保留指定Asset Bundle")]
        private static void CherryPickResources()
        {
            string file = EditorUtility.OpenFilePanel("打开resources文件", "", "txt");
            if (string.IsNullOrEmpty(file))
                return;

            CherryPickResources(file);
        }

        public static void CherryPickResources(string file)
        {
            var neededResources = new HashSet<string>();
            using (var streamReader = new StreamReader(File.OpenRead(file)))
            {
                while (!streamReader.EndOfStream)
                {
                    string line = streamReader.ReadLine();
                    var substrings = line.Split(',');

                    // assets/arts/character/item/map/newnew/mat/tex_skybox_v1_png
                    string path = substrings[0];
                    neededResources.Add(path);
                }
            }

            var files = Directory.GetFiles("Assets/StreamingAssets/assets", "*.dat", SearchOption.AllDirectories);
            foreach (var s in files)
            {
                string path = s.Replace("\\", "/");
                if (path.Contains("/lua/"))
                    continue;

                path = path.Substring("Assets/StreamingAssets/".Length).Replace(".dat", "");
                if (neededResources.Contains(path))
                    continue;

                File.Delete(s);
                File.Delete(s + ".meta");
            }

            AssetStandardHelper.RemoveEmptyFolder("Assets/StreamingAssets/assets");

            Debug.Log("清理完毕");
        }
    }
}
